package com.zcyr.controller.interceptor;

import com.zcyr.constant.StatusCode;
import com.zcyr.pojo.UserInfo;
import com.zcyr.util.JsonBody;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

@Component
public class AuthControlInterceptor implements HandlerInterceptor {
    @Value("${tryme.enabledGiteeAuth:true}")
    boolean enableGiteeAuth;

    @Override
    public boolean preHandle(HttpServletRequest request, @NonNull HttpServletResponse response, @NonNull Object handler) throws Exception {
        if(request.getMethod().equalsIgnoreCase("OPTIONS")){
            return true; //通过所有OPTION请求
        }

        if(!enableGiteeAuth){
            response.setHeader("Access-Control-Allow-Credentials", "true");
            response.setContentType("application/json; charset=UTF-8");
            PrintWriter out = response.getWriter();
            out.print(JsonBody.custom(StatusCode.NOT_LOGIN,"无法操作, 请确保服务器启用了tryme.enabledGiteeAuth配置"));
            out.close();
            return false;
        }
        return HandlerInterceptor.super.preHandle(request, response, handler);
    }
}
